package com.fly.caihong.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * 创建时间：2018/5/25 0025 11:50
 * 创建人：fly
 * 功能描述：实现懒加载的Fragment
 */
public abstract class BaseFragment extends Fragment {

    /**
     * 父activity
     */
    protected BaseActivity mActivity;
    /**
     * 是否已经创建视图
     */
    protected boolean isViewCreated = false;

    /**
     * 是否已加载完数据
     */
    protected boolean isLoadDataCompleted = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (BaseActivity) getActivity();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        //对于单个fragment是不会调用该方法的，只适用于ViewPager控件包裹的Fragment，当切换他们的可见性时会执行以下代码
        if (isVisibleToUser && isViewCreated && !isLoadDataCompleted) {
            initData();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(getLayout(), container, false);
        initView(rootView);
        initListener();
        isViewCreated = true;
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //默认首先显示第一个Fragment，所以这个地方还是要调用一次，不然第一个Fragment不会加载数据
        if (getUserVisibleHint()) {
            initData();
        }
    }

    /**
     * 显示加载进度条
     */
    protected void showLoading() {
        mActivity.showLoading();
    }

    /**
     * 显示加载进度条
     *
     * @param msg
     */
    protected void showLoading(String msg) {
        mActivity.showLoading(msg);
    }

    /**
     * 显示加载进度条
     *
     * @param resId
     */
    protected void showLoading(@StringRes int resId) {
        mActivity.showLoading(resId);
    }

    /**
     * 替换显示内容
     *
     * @param msg
     */
    protected void replaceLoading(String msg) {
        mActivity.replaceLoading(msg);
    }

    /**
     * 移除加载进度条
     */
    protected void dismissLoading() {
        mActivity.dismissLoading();
    }

    /**
     * 初始化数据
     */
    public void initData() {
        isLoadDataCompleted = true;
    }

    /**
     * 初始化监听器
     */
    protected void initListener() {
    }

    /**
     * 初始化View
     *
     * @param view
     */
    protected abstract void initView(View view);

    /**
     * 布局视图xml
     *
     * @return
     */
    protected abstract int getLayout();

}
